package com.cskaoyan.user.utils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {

    public static String getMd5(String content) throws Exception {
        //获得消息消息摘要算法
        MessageDigest messageDigest = MessageDigest.getInstance("md5");
        byte[] contentBytes = content.getBytes();
        byte[] resultBytes = messageDigest.digest(contentBytes);//byte 8 2^8 ff
        int length = resultBytes.length;
        System.out.println("length:" + length);
        StringBuffer stringBuffer = new StringBuffer();
        for (byte resultByte : resultBytes) {
            int temp = resultByte&0xff; //0-255
            String s = Integer.toHexString(temp); //0-15 0a  05 0-f
            if (s.length() == 1){
                stringBuffer.append(0);
            }
            stringBuffer.append(s);
        }
        return stringBuffer.toString();


    }
    public static String getMd5(String content,String salt) throws Exception {
        content = content + "&"  + salt + "}";
        return getMd5(content);
    }

    public static String getMultyMd5(String content) throws Exception {
        return getMd5(getMd5(getMd5(content)),"123456");
    }

    public static String getFileMd5(File file) throws Exception{
        MessageDigest messageDigest = MessageDigest.getInstance("md5");

        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = fileInputStream.read(bytes,0,1024)) != -1){
            messageDigest.update(bytes,0,bytes.length);
        }
        byte[] resultBytes = messageDigest.digest();
        StringBuffer stringBuffer = new StringBuffer();
        for (byte resultByte : resultBytes) {
            int temp = resultByte&0xff; //0-255
            String s = Integer.toHexString(temp); //0-15 0a  05 0-f
            if (s.length() == 1){
                stringBuffer.append(0);
            }
            stringBuffer.append(s);
        }
        return stringBuffer.toString();
    }
}
